/*
 * @Author: hongbin
 * @Date: 2022-12-08 11:44:34
 * @LastEditors: hongbin
 * @LastEditTime: 2023-03-31 20:27:00
 * @Description:好友管理
 */
import { FC, memo, useCallback, useEffect, useState } from "react";
import styled from "styled-components";
import { post } from "../../api";
import { useAuth } from "../../context/AuthProvide";
import { IFriends, UserInfo } from "../../hook/useRegisterForm";
import { flexCenter } from "../../styled";

interface IProps {
    friends: IFriends[];
}

const FriendManage: FC<IProps> = ({ friends }) => {
    const [friendsInfo, setFriendsInfo] = useState<UserInfo[]>([]);
    const [loading, setLoading] = useState(false);

    const query = useCallback(async (friends: IFriends[]) => {
        setLoading(true);
        const { data } = await post("/FriendsList/queryFriendsInfo", {
            friendsList: friends,
        });
        setLoading(false);
        setFriendsInfo(data);
    }, []);

    useEffect(() => {
        if (friends.length) {
            query(friends);
        }
    }, [friends, query]);

    return (
        <Container>
            <h3>好友管理</h3>
            {friends.length ? (
                loading ? (
                    <div>loading..</div>
                ) : (
                    friendsInfo.map((friend, i) => (
                        <FriendItem friendItem={friends[i]} friend={friend} key={friend._id} />
                    ))
                )
            ) : (
                "暂无好友，快去认识吧"
            )}
        </Container>
    );
};

interface IFriendItem {
    friend: UserInfo;
    friendItem: IFriends;
}

const FriendItem: FC<IFriendItem> = ({ friend, friendItem }) => {
    const { user, recordUserInformation } = useAuth();

    const deleteFriend = () => {
        if (confirm("删除")) {
            post(`/FriendsList/del`, {
                friendItem,
                userId: user._id,
            }).then((res) => {
                console.log(res);
            });
        }
    };

    return (
        <div className="item">
            <Name>{friend.name}</Name>
            <button onClick={deleteFriend}>删除</button>
        </div>
    );
};

export default memo(FriendManage);

const Name = styled.span``;

const Container = styled.div`
    background: #033c00;
    padding: 1vh 1vw;
    color: #fffae5;
    font-size: max(13px, 1vw);
    border-radius: 1vw;
    min-width: 10vw;
    min-height: 10vw;
    min-width: 15vmax;

    .item {
        ${flexCenter};
        justify-content: space-between;
        margin-top: 1vmin;
    }

    button {
        margin-left: 1vmin;
    }
`;
